package com.cqy.resource2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    public static final String RESOURCE_ID = "res2";

    public ResourceServerConfig() {
        super();
    }

    @Autowired
    RemoteTokenServices remoteTokenServices;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);

        resources.resourceId(RESOURCE_ID)
                .tokenServices(remoteTokenServices)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r2/**").access("#oauth2.hasAnyScope('scopes2','scopes3')")
                .anyRequest().permitAll();
    }
}
